// 调用接口
import { loginApi } from '@/api/auth/index';
import {getInfo } from '@/api/user/index';
// 接口类型
import type { LoginData } from '@/api/auth/types';
import type {UserInfo, UserQuery,UserPageV0,UserForm } from '@/api/user/model';
// pinia
import { defineStore } from 'pinia'
import {resetRouter} from '@/router'
import {store} from '@/stores/index'
import {TOKEN_KEY} from '@/enums/CacheEnum'

export const useUserStore = defineStore("user", () => {
  const user = ref<UserInfo>({
    roles: [],
    perms: [],
  });
  /**登录
   * 
   * @param {LoginData}
   * @returns
   *  
   */ 
  function login(loginData:LoginData){
    return new Promise<void>((resolve,reject)=>{
      loginApi(loginData).then((data)=>{    
        const {tokenType,accessToken} =data
        localStorage.setItem(TOKEN_KEY, 
          tokenType + " " + accessToken);
        resolve()
      }).catch((error)=>{
        reject(error)
      })
    })
  }

  // 获取信息(用户昵称/头像/角色集合/权限集合)
  function getUser(){
    
    return new Promise<UserInfo>((resolve,reject)=>{
      getInfo().then((data)=>{
        
        if (!data) {
          reject("验证失败,请重新登录");
          return
        }
        if (!data.roles ||data.roles.length <=0) {
          reject("getUserInfo:角色必须是非空数组")
          return
        }
        Object.assign(user.value,{...data})
        resolve(data)
      }).catch((error)=>{
        reject(error)
      })
    })
  }
    // 移除 token
    function resetToken(){
      return new Promise<void>((resolve)=>{
        localStorage.setItem(TOKEN_KEY,"");
        resetRouter()
        resolve()
      })
    }
  return {
    login,
    resetToken,
    getUser,
    user
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}